import torchvision
from torch import nn
from torchvision.transforms import transforms
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.nn.functional as F
import torch.optim as optim

transform = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])

# 第一步：加载数据集
train_set = torchvision.datasets.CIFAR10(root='../data', train=True, download=True,
                                         transform=transform)
train_loader = torch.utils.data.DataLoader(train_set, batch_size=4, shuffle=True, num_workers=0)

test_set = torchvision.datasets.CIFAR10(root='../data', train=False, download=True,
                                        transform=transform)
test_loader = torch.utils.data.DataLoader(test_set, batch_size=4, shuffle=False, num_workers=0)

# 中文标签
classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')


# 构建展示图片展示的函数
def imshow(img):
    img = img / 2 + 0.5
    npimg = img.numpy()
    plt.imshow(np.transpose(npimg, (1, 2, 0)))
    plt.show()


# # 从数据迭代器种读取一张图片
# dataiter = iter(test_loader)
# images, labels = next(dataiter)  # 修改这里：使用next()函数
# # 展示图片
# imshow(torchvision.utils.make_grid(images))
# print(' '.join('%5s' % classes[labels[j]] for j in range(4)))


# 第二步：定义网络结构
class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(3, 6, 5)
        self.pool = nn.MaxPool2d(2, 2)
        self.conv2 = nn.Conv2d(6, 16, 5)
        self.fc1 = nn.Linear(16 * 5 * 5, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)

    def forward(self, x):
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        # 变换x的形状，适应全连接层的输入
        x = x.view(-1, 16 * 5 * 5)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x


net = Net()
# print(net)

# 第三步：定义损失函数和优化器，选用 交叉熵损失函数 和 随机梯度下降优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)

# # 第四步：在训练集上训练模型
# for epoch in range(2):
#     running_loss = 0.0
#     # 按批次迭代训练集
#     for i, data in enumerate(train_loader, 0):
#         # 从data中获取输入和标签
#         inputs, labels = data
#         # 1. 清零梯度
#         optimizer.zero_grad()
#         # 2. 前向传播
#         outputs = net(inputs)
#         loss = criterion(outputs, labels)
#         # 3. 反向传播
#         loss.backward()
#         optimizer.step()
#
#         # 打印训练信息
#         running_loss += loss.item()
#         if i % 2000 == 0:
#             print(f'[epoch:{epoch + 1}, batch:{i + 1:5d}] loss:{running_loss / 2000}')
#             running_loss = 0.0
# print('Finished Training')
#
# # 设定模型保存位置
model_save_path = './model_save/cifar_cnn_net.pth'
# # 保存模型的状态字典
# torch.save(net.state_dict(), model_save_path)

#  第五步：在测试集上测试模型
# 打印测试集的图片
data_iter = iter(test_loader)
images, labels = next(data_iter)
# 打印原始图片
# imshow(torchvision.utils.make_grid(images))
# print('GroundTruth: ', ' '.join(f'{classes[labels[j]]:5s}' for j in range(4)))

# 加载模型并对测试集进行测试
"""
未来版本将默认改为weights_only=True

这种模式更安全，但限制更多
"""
net.load_state_dict(torch.load(model_save_path, weights_only=True))
# 利用模型对测试集进行预测
output = net(images)
# 模型有10个类，选取最大的预测结果
_, predicted = torch.max(output, 1)
# print('Predicted: ', ' '.join(f'{classes[predicted[j]]:5s}' for j in range(4)))

# 在整个测试集上测试模型的准确率
correct = 0
total = 0
with torch.no_grad():
    for data in test_loader:
        images, labels = data
        outputs = net(images)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()
print(f'Accuracy of the network on the 10000 test images: {100 * correct // total} %')